package cn.cuilan.test.thread;

/**
 * 三线程交替打印ABC
 *
 * @author zhang.yan
 * @since 2021/6/1
 */
public class ABCThread extends Thread {

    private String name;
    private Object pre;
    private Object current;

    public ABCThread(String name, Object pre, Object current) {
        this.name = name;
        this.pre = pre;
        this.current = current;
    }

    @Override
    public void run() {
        int count = 10;
        while (count > 0) {
            synchronized (pre) {
                synchronized (current) {
                    System.out.println(name);
                    count--;
                    current.notifyAll();
                }
                if (count == 0) {
                    pre.notifyAll();
                } else {
                    try {
                        pre.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();

        ABCThread t1 = new ABCThread("A", c, a);
        ABCThread t2 = new ABCThread("B", a, b);
        ABCThread t3 = new ABCThread("C", b, c);

        t1.start();
        Thread.sleep(2L);
        t2.start();
        Thread.sleep(2L);
        t3.start();
    }
}
